package org.jeecg.modules.wei.util;

import java.net.InetAddress;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.util.HttpRequest;

import com.alibaba.fastjson.JSONObject;






public class WeiboUtils {
	
	public static String client_id = "3272195192";
	public static String client_sercret = "c15358d30fe5a236f0c4915ca131e250";
    public static String redirect_url = "http://gongan.hbweiyinqing.cn/f/dataapp/api/oauth2/authorize";
    public static String base_url = "https://api.weibo.com/2/";
    public static String access_token_url = "https://api.weibo.com/oauth2/access_token";
    public static String authorize_url = "https://api.weibo.com/oauth2/authorize";
    public static String rm_url = "https://rm.api.weibo.com/2/";
    
    public static void main(String[] args) {
		//String code = "d5184e58c419946344f55f8080cece6f";
		//getAccessTokenByCode(code);
    	//getCommentToMe("2.00XrwF3Ho8n8ZD82b1f277a9xlJV7B", "1", "20");
    	//showUserById("2.00XrwF3Ho8n8ZD82b1f277a9xlJV7B", "6739427127");
    	//getCommentToMe("2.00XrwF3Ho8n8ZD82b1f277a9xlJV7B", "1", "20");
    	//getCommentToMe(access_token, "1", "10");
		
		//
		
		//getCommentToMe(access_token, "1", "20");
    	//getCommentById(access_token, "6739427127","1", "10");

		//String access_token = get_token();
		//getUserTimeline(access_token, "0", "10");
//		System.out.println(access_token);
		//getCommentToMe(access_token, "1", "20");
    	
    	
//    	String accessToken = "2.00NeCenHXIQtsBdb00039e90d2myHD";
//    	other();
    

	}
    /**
     * 批量获取用户信息
     * @return
     */
//    public static String other() {
//
//    	Map<String,String> paramsMap = new HashMap<>();
//        paramsMap.put("uids",1808545011);
//
//
//    	
//		String result = HttpRequest.httpPostWithJSON("https://c.api.weibo.com/2/users/show_batch/other.json", param);
//		String result = HttpRequest.sendGet("https://c.api.weibo.com/2/users/show_batch/other.json", "");
//		System.out.println("获取token"+result);
//		JSONObject json = JSONObject.parseObject(result);
//		if(json.getString("code").equals("200")) {
//			return json.getString("token");
//		}else {
//			return  null;
//		}
//	}
    
    

    
    
    public static String get_token() {
		String result = HttpRequest.sendGet("http://gongan.hbweiyinqing.cn/f/dataapp/api/get_access_token", "");
		System.out.println("获取token"+result);
		JSONObject json = JSONObject.parseObject(result);
		if(json.getString("code").equals("200")) {
			return json.getString("token");
		}else {
			return  null;
		}
	}
 
    
    public static String authorize(String response_type) {
		return authorize_url.trim() + "?client_id="
				+ client_id.trim() + "&redirect_uri="
				+ redirect_url.trim()
				+ "&response_type=" + response_type;
	}
    
    public static JSONObject getAccessTokenByCode(String code) {
    	Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("client_id",client_id);
        paramsMap.put("client_secret",client_sercret);
        paramsMap.put("grant_type","authorization_code");
        paramsMap.put("code",code);
        paramsMap.put("redirect_uri",redirect_url);
    
        //post方式请求并输出接口响应结果
        String result = sendPost(access_token_url,paramsMap);
        System.out.println(result);
        return JSONObject.parseObject(result);
	}
    
    

    
    public static JSONObject showUserById(String accessToken,String uid) {
    	Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("uid",uid);

    
        //post方式请求并输出接口响应结果
        String result = sendGet(accessToken, base_url + "users/show.json",paramsMap);
        return JSONObject.parseObject(result);
	
	}
   /**
    * 获取当前登录用户所接收到的评论列表
    * @param accessToken
    * @param page
    * @param count
    * @return
    */
	public static JSONObject getCommentToMe(String accessToken, String page,
			String count){
		Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("page",page);
        paramsMap.put("count",count);

    
        //post方式请求并输出接口响应结果
        String result = sendGet(accessToken,base_url + "comments/to_me.json",paramsMap);
        System.out.println(result);
        return JSONObject.parseObject(result);
	}
	
	public static JSONObject getCommentById(String accessToken, String id,String page,
			String count){
		Map<String,String> paramsMap = new HashMap<>();
		paramsMap.put("id",id);
		paramsMap.put("page",page);
		paramsMap.put("count",count);
		
		//post方式请求并输出接口响应结果
		String result = sendGet(accessToken,base_url + "comments/show.json",paramsMap);
		System.out.println(result);
		return JSONObject.parseObject(result);
	}
	
	public static JSONObject getUserTimeline(String accessToken, String page,
			String count){
		Map<String,String> paramsMap = new HashMap<>();
		paramsMap.put("page",page);
		paramsMap.put("count",count);

		
		//post方式请求并输出接口响应结果
		String result = sendGet(accessToken,base_url + "statuses/user_timeline.json",paramsMap);
		System.out.println(result);
		return JSONObject.parseObject(result);
	}
	
	
	public static JSONObject getHomeTimeline(String accessToken, String page,
			String count){
		Map<String,String> paramsMap = new HashMap<>();
		paramsMap.put("page",page);
		paramsMap.put("count",count);
		
		
		//post方式请求并输出接口响应结果
		String result = sendGet(accessToken,base_url + "/statuses/home_timeline.json",paramsMap);
		System.out.println(result);
		return JSONObject.parseObject(result);
	}
	public static JSONObject getPublicTimeline(String accessToken, String page,
			String count){
		Map<String,String> paramsMap = new HashMap<>();
		paramsMap.put("page",page);
		paramsMap.put("count",count);
		
		
		//post方式请求并输出接口响应结果
		String result = sendGet(accessToken,base_url + "/statuses/repost_timeline.json",paramsMap);
		System.out.println(result);
		return JSONObject.parseObject(result);
	}
    
    
    
    /**
     * 发送POST请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendPost(String url, Map<String, String> params) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String urlWithParams = url;
        String rtnStr = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(urlWithParams);

            if (params != null && !params.isEmpty()) {
                List<NameValuePair> postParams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    postParams.add(new BasicNameValuePair(entry.getKey(), entry
                            .getValue()));
                }

                urlWithParams += "?"
                        + StringUtils.join(postParams.toArray(), "&");

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                        postParams, "UTF-8");
                httpPost.setEntity(entity);
            }
            System.out.println("POST URL = [" + urlWithParams + "]");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = httpResponse.getEntity();
                rtnStr = EntityUtils.toString(resEntity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpPost != null)
                httpPost.releaseConnection();
        }
        return rtnStr;
    }

    /**
     * 发送Get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendGet(String token, String url, Map<String, String> params) {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String urlWithParams = url;
        String rtnStr = null;
        try {
            httpClient = new SSLClient();
            
//            
           

  
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> getParams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    getParams.add(new BasicNameValuePair(entry.getKey(), URLEncoder.encode(entry
                            .getValue(),"utf-8")));
                }
                urlWithParams += "?"
                        + StringUtils.join(getParams.toArray(), "&");
            }
            httpGet = new HttpGet(urlWithParams);
            if(StringUtils.isNotEmpty(token)) {
            	InetAddress ipaddr = InetAddress.getLocalHost();
                httpGet.setHeader("Authorization", "OAuth2 " + token);  
                httpGet.setHeader("API-RemoteIP", ipaddr.getHostAddress());  
            }
            System.out.println("Get URL = [" + urlWithParams + "]");
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = httpResponse.getEntity();
                rtnStr = EntityUtils.toString(resEntity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpGet != null)
                httpGet.releaseConnection();
        }
        return rtnStr;
    }
}


class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}
